package com.lottery.module.service;

import com.lottery.entity.LotteryInfo;
import com.lottery.module.dao.LotteryInfoDao;
import com.lottery.util.DateUtil;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LotteryInfoService
{

  @Autowired
  private LotteryInfoDao lotteryInfoDao;

  @Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
  public LotteryInfo findNotEndInfo()
  {
    LotteryInfo info = this.lotteryInfoDao.findNotEndInfo();
    return info;
  }

  @Transactional(propagation=Propagation.REQUIRED, rollbackFor={RuntimeException.class}, readOnly=false)
  public void startNextLottery() {
    LotteryInfo info = this.lotteryInfoDao.findNotEndInfo();
    if (info == null) {
      DecimalFormat df = new DecimalFormat("0000");
      info = new LotteryInfo();
      info.setPeriods(DateUtil.getYear() + df.format(DateUtil.getWeekNumber()));
      info.setSaleTotalMoney(BigDecimal.ZERO);
      info.setSaleTotalCount(0);
      info.setHasEnd(false);
      info.setLotteryTime(null);
      info.setLotteryResult(null);
      info.setCreateTime(new Date());
      info.setUpdateTime(new Date());
      info.setVersion(0);
      this.lotteryInfoDao.insert(info);
    }
  }
}